window.Pinion = {};


$( document ).ajaxError(( event, jqxhr, settings, exception ) ->
    if jqxhr.status == 403
        Pinion.ajaxLogin()
)

Pinion.ajaxLogin = (callback=($n) -> $n.remove())->
    console.log(arguments)
    $content = $("""
                <div class='login-form'>
                    <label>
                        <input placeholder='账号 / 邮箱 / 手机号' class='account' name='account' type='text'>
                    </label>
                    <label>
                        <input placeholder='密码' class='password' name='password' type='password'>
                    </label>
                </div>
                """)
    $notify = Pinion.notify( $content, ($notifyContent)->
        console.log($notifyContent)
        # OkCB
    , (e, $notify)->
        jqxhr = $.post("/login", {
            account: $content.find("input[name='account']").val()
            password: $content.find("input[name='password']").val()
            template: "/freemarker/fw/navbar_top.ftl"
        })

        jqxhr.done (response)->
            $navbarTop = $(response)
            $old = $(".navbar-fixed-top")
            $old.before($navbarTop)
            $(".navbar-fixed-top").animate({top: -50},500, ->
                    $old.remove()
                    $navbarTop.animate({top: 0})
            )
            $notify.fadeOut()
            Pinion.simpleNotify("登陆成功")
            callback($notify)

        jqxhr.fail ()->
            console.log(arguments)
        # cancelCB
    , (e)->
        console.log(e)
    )

commentFn = (clazz, id, content, done=->) ->
    jqxhr = $.post("/comment/create", {
        id: id
        clazz: clazz,
        content: content
    });
    jqxhr.done(done);


Pinion.createComment = (clazz, id, $textarea = $(".comment-post-box textarea"), $commenList = $(".comment-list")) ->
    if(!$textarea.val())
        return;
    commentFn(clazz, id, $textarea.val(), (response) ->
        $textarea.val("")
        $commenList.prepend($("<li></li>").html($(response)))
    )

Pinion.replyToComment = (clazz, id, el) ->
    $item = $(el).closest(".comment-item")
    if($item.find("#reply_comment").length > 0)
        return $item.find("#reply_comment").remove()
    $commentArea = $("#reply_comment")
    if($commentArea.length > 0)
        $commentArea.remove()
    $commentArea = $("""
                     <div id='reply_comment'><textarea></textarea><span class='btn btn-default submit'>确定</span></div>
                     """)
    $(el).after($commentArea)
    $submit = $commentArea.find(".submit")
    $textarea = $commentArea.find("textarea")
    $textarea.focus()
    $submit.click(->
        if(!$textarea.val())
            return
        commentFn(clazz, id, $textarea.val(), (response) ->
            $commentArea.remove()
            $(".comment-list").prepend($("<li></li>").html($(response)))
        )
    )

###
    Like Something like somebook, somebody somepost
###
Pinion.like = (clazz, id, el) ->
    $.get("/like", {
        clazz: clazz,
        id: id
    }, (response)->
        $(el).html("不喜欢了").attr({"onclick": "Pinion.unLike('#{clazz}', #{id}, this)" }).addClass("undo")
        likeCountEl = $("#book_preview_page_#{id} .like-count")
        if(likeCountEl.length > 0)
            likeCountEl.html(parseInt(likeCountEl.text()) + 1)
    )

Pinion.unLike = (clazz, id, el) ->
    $.get("/like/undo", {
            clazz: clazz,
            id: id
        }, (response)->
            $(el).html("喜欢").attr({"onclick": "Pinion.like('#{clazz}', #{id}, this)" }).removeClass("undo")
            likeCountEl = $("#book_preview_page_#{id} .like-count")
            if(likeCountEl.length > 0)
                likeCountEl.html(parseInt(likeCountEl.text()) - 1)
    )


###
    Collect Something like somebook, somebody somepost
###
Pinion.favorite = (clazz, id, el) ->
    $cont = undefined
    $content = $("""
                <div class='tag-box' style='width: 380px; margin: auto;background-color: #fff; text-align: left;'>
                    <input type='text' class='tag-input' style='width: 78px; border: #fff;' placeholder='标签'>
                </div>
                """)
    $notify = Pinion.notify($content, ($content)->

        $cont = $content;
        $content.on("click", ->
            $content.find(".tag-input").focus()
        )
        $content.find(".tag-input").on("keydown", (e)->
            if(e.keyCode == 13 && $(e.target).val())
                $(e.target).before($("""<span class="tag label label-primary" style='font-size: 16px;'>#{$(e.target).val()}</span>"""))
                $(e.target).val("")
            if(e.keyCode == 8 && !$(e.target).val())
                $(e.target).prev().remove()
        )

        $.get("/tag/top3"
            , { clazz: clazz, id: id }
            , (response)->
                $.each(response, (index, obj)->
                    $tag = $("""<span class="tag label label-primary" style='font-size: 16px;'>#{obj.name}</span>""")
                    $content.find(".tag-input").before($tag)
                )
        )

    , (e)->
        jqxhr = $.get("/favorite", {
            clazz: clazz,
            id: id
            tag: $(tag).text() for tag in $cont.find(".tag")
        }, (response)->
            Pinion.simpleNotify(message: "收藏成功")
            $(el).html("取消收藏").attr({"onclick": "Pinion.unFavorite('#{clazz}', #{id}, this)" }).addClass("undo")
            favoCountEl = $("#book_preview_page_#{id} .favo-count")
            if(favoCountEl.length > 0)
                favoCountEl.html(parseInt(favoCountEl.text()) + 1)
            $notify.fadeOut()
        )
    ,(e)->
        console.log(e)
    )


Pinion.unFavorite = (clazz, id, el) ->
    $.get("/favorite/undo", {
            clazz: clazz,
            id: id
        }, (response)->
            $(el).html("收藏").attr({"onclick": "Pinion.favorite('#{clazz}', #{id}, this)" }).removeClass("undo")
            favoCountEl = $("#book_preview_page_#{id} .favo-count")
            if(favoCountEl.length > 0)
                favoCountEl.html(parseInt(favoCountEl.text()) - 1)
    )


###
    Visit some page like a book or a chapter, of course someone's page
###
Pinion.visit = (clazz, id) ->
    $.get("/visit",{
        clazz: clazz,
        id: id
    });

###
   Add tag for something
###
Pinion.tag = (clazz, id) ->
    $.get("/tag", {
        clazz: clazz,
        id: id
    }, (response)->
        Pinion.simpleNotify(message: "分类成功")
        console.log(response)
    )




Pinion.subscribe = (id)->
    $.get("/tag/subscribe", { id: id}).done(-> Pinion.simpleNotify("订阅成功"))

###
    notify
###
Pinion.simpleNotify = (options={message: "notify"}) ->
    if typeof options == "string"
        options = {message: options}
    options.afterShow = options.afterShow || ->
        setTimeout(->
            $notify.fadeOut("slow", ->
                $notify.fadeOut()
            )
        , 1000)

    $notify = $("""<div id="notify_pop_#{new Date().getTime()}" class='simple-notify'>#{options.message}</div>""")
    $("body").append($notify);
    $notify.animate({top: "30%", display: "block"},"slow", ->
        options.afterShow($notify)
    )
    $notify

###
    complex notify
###
Pinion.notify = ($content, callback=(->), okCB = (->), cancelCB=(->)) ->
    $notify = $("""<div id="notify_pop_#{new Date().getTime()}"
                        class='notify_pop_box'>
                <div class='notify_content'></div>
                <div>
                    <span class='ok-notify' >Ok</span>
                    <span class='cancel-notify' >Cancel</span>
                </div>
                </div>""")
    $("body").append($notify);
    $notify.find(".notify_content").html($($content))
    $notify.animate({top: "30%", display: "block"},200)
    $notify.find(".cancel-notify")
        .on("click", (e)->
            cancelCB(e, $notify)
        )
        .on("click", ()->
            $notify.fadeOut(200)
        )
    $notify.find(".ok-notify").on("click", (e)->
        okCB(e, $notify)
    )
    callback($notify.find(".notify_content"))
    return $notify



###
    type: Class
    options
        (base)
        - $el
        - content
        - callback

        (advance)
        - moveH
        - moveV
###
class Pinion.Tooltip
    constructor: (options)->
        self = @
        @options = options
        @$el = options.$el
        @content = options.content
        @callback = options.callback || ->

        @moveH = options.moveH || 0
        @moveV = options.moveV || 0
        @top = @$el.offset().top + @moveV
        @left = @$el.offset().left + @moveH

        @$tooltip = $(""" <div id='tooptip_#{new Date().getTime()}' class='tooltip'> </div>""")
        @$content = $(@content)
        @$tooltip.html(@$content)

        @isHover = true
        @$el.on("mouseenter", -> self.isHover = true).on("mouseleave", -> self.isHover = false)
        @$tooltip.on("mouseenter", -> self.isHover = true).on("mouseleave", -> self.isHover = false)
        @$tooltip.addClass(@options.className || "")
        @callback(@$tooltip)
        @css({top: "#{@top}px",  left: "#{@left}px", width: "#{@options.width || 100}px", height: "#{@options.height || 100}px"})

    loopFn: ->
        self = @
        setTimeout(->
            if(self.isHover)
                self.loopFn()
            else
                self.$tooltip.fadeOut("fast", ->
                    self.$tooltip.remove()
                )
        , 1500)

    css: (obj) ->
        @$tooltip.css(obj)
    show: (obj = {})->
        $("body").append(@$tooltip)
        @loopFn()
        @css(obj)


###

###
class Pinion.Loading
    constructor: ->
        @$notify = Pinion.simpleNotify({
            message: "Loading"
            afterShow: ($notify)->
                console.log($notify)
        })
    over: ->
        self = @
        @$notify.fadeOut(->self.$notify.remove())



#$( ()-> $("head").append($(""" <script src="/book/static/events.js"></script> """)) )